export default function tooltipsPlugin(opts) {
  function init(u, opts, data) {
    let plot = u.root.querySelector('.u-over')

    let ttc = (u.cursortt = document.createElement('div'))
    ttc.className = 'tooltip'
    ttc.style.pointerEvents = 'none'
    ttc.style.position = 'absolute'
    plot.appendChild(ttc)

    u.seriestt = opts.series.map((s, i) => {
      if (i === 0) return

      let tt = document.createElement('div')
      tt.className = 'tooltip'
      tt.style.pointerEvents = 'none'
      tt.style.position = 'absolute'
      tt.style.background = 'rgba(0,0,0,0.8)'
      tt.style.color = '#ffffff'
      tt.style.padding = '2px 4px'
      tt.style.fontSize = '12px'
      tt.style.borderRadius = '2px'
      tt.style.display = s.show ? null : 'none'
      plot.appendChild(tt)
      return tt
    })

    function hideTips() {
      ttc.style.display = 'none'
      u.seriestt.forEach((tt, i) => {
        if (i === 0) return

        tt.style.display = 'none'
      })
    }

    function showTips() {
      ttc.style.display = null
      u.seriestt.forEach((tt, i) => {
        if (i === 0) return

        let s = u.series[i]
        tt.style.display = s.show ? null : 'none'
      })
    }

    plot.addEventListener('mouseleave', () => {
      if (!u.cursor._lock) {
        //	u.setCursor({left: -10, top: -10});
        hideTips()
      }
    })

    plot.addEventListener('mouseenter', () => {
      showTips()
    })

    hideTips()
  }

  function setCursor(u) {
    const { left, top, idx } = u.cursor

    // u.cursortt.style.left = left + 'px'
    // u.cursortt.style.top = top + 'px'
    // u.cursortt.textContent =
    //   '(' +
    //   u.posToVal(left, 'x').toFixed(2) +
    //   ', ' +
    //   u.posToVal(top, 'y').toFixed(2) +
    //   ')'

    // can optimize further by not applying styles if idx did not change
    u.seriestt.forEach((tt, i) => {
      if (i === 0) return

      let s = u.series[i]

      if (s && s.show) {
        let xVal = u.data[0][idx]
        let yVal = u.data[i][idx]

        if (typeof xVal === 'number') {
          xVal = xVal.toFixed(2)
        }

        if (yVal === null) {
          tt.style.display = 'none'
          return
        }

        if (typeof yVal === 'number') {
          yVal = yVal.toFixed(2)
        }

        tt.textContent = `x: ${xVal} y: ${yVal}` // s.label

        tt.style.display = 'block'
        tt.style.left = Math.round(u.valToPos(xVal, 'x')) + 'px'
        tt.style.top = Math.round(u.valToPos(yVal, s.scale)) + 'px'
      }
    })
  }

  return {
    hooks: {
      init,
      setCursor
    }
  }
}
